﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-tabs v-model="activeTab">
			<el-tab-pane label="基础信息" name="main">
				<el-card shadow="hover" class="layout-padding-auto create-form">
					<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>单据信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
										<template #label>
											<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.BillCode" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillStatus_FormItem" prop="Entity.BillStatus">
										<template #label>
											<WtmLabelTooltip label="单据状态" tooltip="单据状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.BillStatus" disabled clearable class="width100">
											<el-option v-for="item in BILL_STATUS_OPTIONS" :key="item" :value="item" :label="item"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_WorkflowStatus_FormItem" prop="Entity.WorkflowStatus">
										<template #label>
											<WtmLabelTooltip label="工作流状态" tooltip="工作流状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.WorkflowStatus" disabled clearable class="width100">
											<el-option v-for="item in WORKFLOW_STATUS_OPTIONS" :key="item" :value="item" :label="item"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
										<template #label>
											<WtmLabelTooltip label="备注" tooltip="备注" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Remark" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>续签信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_PersonId_FormItem" prop="Entity.PersonId">
										<template #label>
											<WtmLabelTooltip label="续签员工" tooltip="续签员工" />
										</template>
										<WtmPersonSelector
											v-model="stateData.vmModel.Entity.PersonId"
											:prefill-person="{
												ID: stateData.vmModel.Entity.PersonId,
												Name: stateData.vmModel.Entity.Name,
												StaffNo: stateData.vmModel.Entity.StaffNo,
											}"
											:disabled="true"
											:clearable="false"
										/>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
										<template #label>
											<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.StaffNo" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
										<template #label>
											<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Name" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_PersonContractId_FormItem" prop="Entity.PersonContractId">
										<template #label>
											<WtmLabelTooltip label="原员工合同" tooltip="关联员工合同" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.PersonContractId" disabled clearable class="width100">
											<el-option v-for="item in stateData.AllSysPersonContracts" :key="item.Value" :value="item.Value" :label="item.Text"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_EmploymentType_FormItem" prop="Entity.EmploymentType">
										<template #label>
											<WtmLabelTooltip label="用工形式" tooltip="用工形式" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.EmploymentType" disabled clearable class="width100">
											<el-option key="全职" value="全职" label="全职"></el-option>
											<el-option key="兼职" value="兼职" label="兼职"></el-option>
											<el-option key="实习" value="实习" label="实习"></el-option>
											<el-option key="外包" value="外包" label="外包"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_ContractType_FormItem" prop="Entity.ContractType">
										<template #label>
											<WtmLabelTooltip label="合同类型" tooltip="合同类型" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.ContractType" disabled clearable class="width100">
											<el-option key="固定期限" value="固定期限" label="固定期限"></el-option>
											<el-option key="无固定期限" value="无固定期限" label="无固定期限"></el-option>
											<el-option key="项目合同" value="项目合同" label="项目合同"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>合同信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_ContractNo_FormItem" prop="Entity.ContractNo">
										<template #label>
											<WtmLabelTooltip label="合同编号" tooltip="合同编号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.ContractNo" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_SignDate_FormItem" prop="Entity.SignDate">
										<template #label>
											<WtmLabelTooltip label="签订日期" tooltip="合同签订日期" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.SignDate" disabled clearable class="width100"></el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_ExpireDate_FormItem" prop="Entity.ExpireDate">
										<template #label>
											<WtmLabelTooltip label="到期日期" tooltip="合同到期日期" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.ExpireDate" disabled clearable class="width100"></el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>流程信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Approver_FormItem" prop="Entity.Approver">
										<template #label>
											<WtmLabelTooltip label="审批人" tooltip="流程审批人" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Approver" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_ApprovalTime_FormItem" prop="Entity.ApprovalTime">
										<template #label>
											<WtmLabelTooltip label="审批时间" tooltip="流程审批时间" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.ApprovalTime" disabled clearable class="width100"></el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>附件信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="SelectedContractFilesIds_FormItem" prop="SelectedContractFilesIds">
										<template #label>
											<WtmLabelTooltip label="合同文件" tooltip="上传的合同文件" />
										</template>
										<wtm-upload-file
											v-model="stateData.vmModel.SelectedContractFilesIds"
											disabled
											clearable
											class="width100"
											:multi="true"
										></wtm-upload-file>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>工作信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" prop="Entity.OrgId" :disabled="true" :auth="false" />
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmDeptSelector v-model:model-value="stateData.vmModel.Entity.GroupId" prop="Entity.GroupId" label="所属部门" :disabled="true" :auth="false" />
								</el-col>
							</el-row>
						</div>
					</el-form>
				</el-card>
			</el-tab-pane>
			<el-tab-pane label="审批信息" key="审批信息">
				<WtmWorkflowTimeline entityType="HengTong.Model.Db.Bill.SysHrRenewRequestBill" :entityId="stateData.vmModel.Entity.ID" />
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.details;false">
import { reactive, ref, getCurrentInstance, onMounted, nextTick, computed, type ComponentInternalInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { SysHrRenewRequestBillApi as api } from '/@/views/hr/syshrrenewrequestbill/api';
import other from '/@/utils/other';
import { useRouter } from 'vue-router';
import { ISysHrRenewRequestBillVm } from '/@/views/hr/syshrrenewrequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import ApproveReasonDialog from '/@/components/approveReason/index.vue';

// 常量定义
const BILL_STATUS_OPTIONS = ['草稿', '正文'] as const;

const WORKFLOW_STATUS_OPTIONS = ['待提交', '提交中', '审核中', '已完成', '已取消'] as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
	IN_AUDIT: '审核中',
	COMPLETED: '已完成',
	CANCELLED: '已取消',
} as const;

const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;

const BUTTON_TEXTS = {
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;

const API_ENDPOINTS = {
	CONTRACTS: '/api/SysHrRenewRequestBill/GetSysPersonContracts',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const activeTab = ref('main');

// 初始化表单数据
const stateData = reactive<IViewModel<ISysHrRenewRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			StaffNo: null,
			Name: null,
			PersonContractId: null,
			EmploymentType: null,
			ContractType: null,
			ContractNo: null,
			SignDate: null,
			ExpireDate: null,
			ContractFiles: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
			OrgId: null,
		},
		ActionName: null,
		IsMyApprove: null,
		SelectedContractFilesIds: null,
		Remark: null,
	},
	AllSysGroups: [],
	AllSysPersonContracts: [],
});

// 计算属性
const isInAudit = computed(() => stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.IN_AUDIT);
const canApprove = computed(() => !!stateData.vmModel.IsMyApprove);

// 统一的成功处理函数
const handleSuccess = () => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '操作成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的审批处理函数
const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api().approve(stateData.vmModel, '').then(handleSuccess).catch(handleError);
		} else {
			loading.value = false;
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 同意
const onAgree = () => {
	other.openDialog('填写同意原因', ApproveReasonDialog, null, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.AGREE);
	});
};

// 拒绝
const onDeny = () => {
	other.openDialog('填写拒绝原因', ApproveReasonDialog, { isRequired: true }, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.REJECT);
	});
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	const routeId = useRouter().currentRoute.value.query.id;

	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	} else if (routeId) {
		stateData.vmModel.Entity.ID = routeId as any;
	}
};

// 加载选择列表数据
const loadSelectListData = async () => {
	try {
		const [contracts] = await Promise.allSettled([other.getSelectList(API_ENDPOINTS.CONTRACTS, [], false)]);

		// 处理选择列表结果，即使部分失败也继续
		if (contracts.status === 'fulfilled') stateData.AllSysPersonContracts = contracts.value;
	} catch (error) {
		// 静默处理错误
	}
};

// 加载实体数据
const loadEntityData = async () => {
	if (!stateData.vmModel.Entity.ID) {
		return;
	}

	try {
		const response = await api().get(stateData.vmModel.Entity.ID);
		other.setValue(stateData.vmModel, response);
	} catch (error) {
		ElMessage.error('加载数据失败，请重试');
		throw error;
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;

	try {
		// 首先初始化页面数据（获取ID）
		initializePageData();

		// 并行加载选择列表数据和实体数据
		await Promise.all([loadSelectListData(), loadEntityData()]);
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.AGREE,
			type: 'primary',
			onClick: onAgree,
			visible: isInAudit.value && canApprove.value, // 审批状态且有审批权限时显示同意
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: onDeny,
			visible: isInAudit.value && canApprove.value, // 审批状态且有审批权限时显示拒绝
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
